package com.llcbenwu.provider;

import com.llcbenwu.filter.SmsCodeAuthenticationToken;
import lombok.Data;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * 这个是提供校验逻辑的一个类
 * @author lilinchun
 * @date 2021/10/29 0029 15:34
 */
@Data
public class SmsCodeAuthenticationProvider implements AuthenticationProvider {


    private UserDetailsService userDetailsService;

    //这里是进行身份验证逻辑是写在这个类中
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        //这里就是获取我们之前封装的信息
       SmsCodeAuthenticationToken authenticationToken= (SmsCodeAuthenticationToken) authentication;
       //authenticationToken.getPrincipal()就是获取我们将mobile的信息
        UserDetails userDetails=userDetailsService.loadUserByUsername((String) authenticationToken.getPrincipal());
       if(userDetails ==null ){
           throw new InternalAuthenticationServiceException("无法获取用户信息");
       }
       //传两个参数用户信息和用户权限
       SmsCodeAuthenticationToken smsCodeAuthenticationToken=new SmsCodeAuthenticationToken(userDetails,userDetails.getAuthorities());
       //将未认证的信息放入到已认证的信息中
        smsCodeAuthenticationToken.setDetails(authenticationToken.getDetails());
        return smsCodeAuthenticationToken;
    }

    //判断是否是我们自己写的token
    @Override
    public boolean supports(Class<?> aClass) {
        return SmsCodeAuthenticationToken.class.isAssignableFrom(aClass);
    }
}
